﻿namespace DCHealthCheck.MvcWeb.Classes {

    #region Usings
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.IO.Compression;
    using System.Web.Mvc; 
    #endregion

    /// <summary>
    /// Custom Action Filter for enabling HTTP compression
    /// </summary>
    public class EnableCompressionAttribute : ActionFilterAttribute {
        private const CompressionMode compress = CompressionMode.Compress;
        public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) {

            HttpRequestBase request = filterContext.HttpContext.Request;
            HttpResponseBase response = filterContext.HttpContext.Response;

            string acceptEncoding = request.Headers["Accept-Encoding"];
            if (String.IsNullOrEmpty(acceptEncoding)) return;

            if (acceptEncoding.ToLower().Contains("gzip")) {
                response.Filter = new GZipStream(response.Filter, compress);
                response.AppendHeader("Content-Encoding", "gzip");
            }
            else if (acceptEncoding.ToLower().Contains("deflate")) {
                response.Filter = new DeflateStream(response.Filter, compress);
                response.AppendHeader("Content-Encoding", "deflate");
            }
        }
    }
}